package com.fc.push.handler;

import com.alibaba.fastjson.JSONObject;
import com.fc.persistence.exception.IDBException;
import com.fc.push.exception.ExcetionLevelConst;
import com.fc.push.exception.MServerException;
import com.fc.push.logger.Applogger;
import com.fc.push.logger.Errorlogger;
import com.fc.remoting.exception.IRemotingException;
import com.fc.remoting.logger.MonitorConfig;
import com.fc.remoting.logger.Monitorlogger;
import com.fc.remoting.protocol.RemotingTcpProtocol;

import io.netty.channel.Channel;

public abstract class AbstractTcpHandler extends RemotingTcpProtocol{

	@Override
	public Object doHandler(Channel channel, JSONObject request) {
		int retryTimes = 0;
		Object object = null;
		while ((retryTimes++) < 3) {
			try {
				Applogger.instance().getLogger().info("commond[{}] body[{}]",
						request.get("module") + ":" + request.get("order"), request.toJSONString());

				object = handle(channel, request);
				return object;
			} catch (MServerException e) {
				if (e.getLevel() == ExcetionLevelConst.EXCEPTION_LEVEL_1) {
					Errorlogger.instance().getLogger().error(e.getMessage(), e);
//					Monitorlogger.monitorLog(MonitorConfig.app, MonitorConfig.exceptionModule, MonitorConfig.MServerException,e,request,object);
					Monitorlogger.monitorLog(MonitorConfig.app, MonitorConfig.exceptionModule, MonitorConfig.Exception,e,request,object);
					return HandlerResult.defaultError();
				} else if (e.getLevel() == ExcetionLevelConst.EXCEPTION_LEVEL_2) {
					Errorlogger.instance().getLogger().error("捕获异常，执行第：" + retryTimes + "】次重做", e);
					Monitorlogger.monitorLog(MonitorConfig.app, MonitorConfig.exceptionModule, MonitorConfig.Exception,e,request,object);
					continue;
				}
			} catch (IDBException e) {
				Errorlogger.instance().getLogger().error(e.getMessage(), e);
//				Monitorlogger.monitorLog(MonitorConfig.app, MonitorConfig.exceptionModule, MonitorConfig.IDBException,e,request,object);
				Monitorlogger.monitorLog(MonitorConfig.app, MonitorConfig.exceptionModule, MonitorConfig.Exception,e,request,object);
				return HandlerResult.defaultError();
			} catch (IRemotingException e) {
				Errorlogger.instance().getLogger().error(e.getMessage(), e);
				Monitorlogger.monitorLog(MonitorConfig.app, MonitorConfig.exceptionModule, MonitorConfig.Exception,e,request,object);
				return HandlerResult.defaultError();
			} catch (Exception e) {
				Errorlogger.instance().getLogger().error(e.getMessage(), e);
				Monitorlogger.monitorLog(MonitorConfig.app, MonitorConfig.exceptionModule, MonitorConfig.Exception,e,request,object);
				return HandlerResult.defaultError();
			}
		}
		return object;
	}
	
	protected abstract Object handle(Channel channel, JSONObject request);
}
